const { tagModel } = require("../models/tag")

class TagController {
  static async getTagByPage(ctx) {
    // 参数校验
    const page = Number(ctx.request.params.page)
    console.log('page:', page)
    console.log('page type:', typeof page)
    ctx.verifyParams({
      page: { type: 'number', required: true },
    }, { page })

    // 业务逻辑/数据库操作
    const num = 8
    const tags = await tagModel.find({}).skip(page * num).limit(num)

    // 返回请求结果
    ctx.succ({
      data: {
        tags
      }
    })
  }

  static async searchTag(ctx) {
    const keyword = ctx.request.params.keyword
    const reg = new RegExp(keyword, 'i') //不区分大小写
    const tags = await tagModel.find({
      name: {
        $regex: reg
      }
    })

    ctx.succ({
      data: {
        tags
      }
    })
  }

  static async addTag(ctx) {
    ctx.verifyParams({
      name: { type: 'string', max: 20, required: true }
    })

    const name = ctx.request.body.name
    const tags = await tagModel.find({
      name
    })

    if (tags.length) {
      ctx.err({
        message: "该标签已存在"
      })
      return
    }

    const newTag = new tagModel({ name })
    const tag = await newTag.save()

    ctx.succ({
      data: {
        tag
      }
    })
  }
}

module.exports = {
  TagController
}